<?php

namespace App\Controller\Home;

use AlibabaCloud\SDK\Sample\Sample;
use App\Controller\Example\VcodeExample;
use App\Models\Conn;
use Core\Common\Common;
use Core\Enums\ErrorEnum;
use Core\Result\Result;
use Core\Utils\Ip\Ipinit;
use Core\Utils\Utils;

class Vcode
{
    /**
     * 发送短信验证码
     * entry phone,type
     * return json
     * */
    public function sendCode($data){
        $VcodeExample = Common::assemble(new VcodeExample(), $data);
        if(!Utils::phoneChecking($VcodeExample->phone)){
            Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT);
        }
        if(!in_array($VcodeExample->type,array(1,2,3,4,5,6,7,8))){
            Result::error(ErrorEnum::STATUSERROR);
        }
        $code = mt_rand(1000,9999);
        $VcodeExample->ip = new Ipinit();
        $VcodeExample->status = 1;
        $conn = new Conn();
        $sql="select UNIX_TIMESTAMP(`time`) as time,`code` from `vcode` where `phone` = '$VcodeExample->phone' and `type` ='$VcodeExample->type' and `ip` = '$VcodeExample->ip' and `status` = '$VcodeExample->status' order by time desc limit 1";
        $data = $conn->readConn($sql);
        /**
         *短信5分钟内不重复发送
         */
        if((time()-$data['time']) < 300){
            Result::error(ErrorEnum::THEVERIFICATIONCODECANNOTBEOBTAINEDREPEATEDLYWITHIN5MINUTES);
        }else{
            $sql="INSERT INTO `vcode`(`phone`, `code`, `type`,`status`,`ip`) VALUES ($VcodeExample->phone,'$code',$VcodeExample->type,'$VcodeExample->status','$VcodeExample->ip')";
            $conn->shiwuStart();
            if($conn->executeConn($sql) !=1){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::THEDATAISBNORMALPLEASELOGOUT);
            }
            $sample = new Sample();
            $sendData["code"]= $code;
            $sendData["phone"]= $VcodeExample->phone;
            $sample::main($sendData);
            $conn->shiwuEnd();
            Result::success("发送成功,请查收");
        }
    }
    /**
     * 验证短信验证码
     * entry VcodeExample
     * return json
     * */
    public function verification($VcodeExample){
        $VcodeExample->ip = new Ipinit();
        $conn = new Conn();
        $sql="select `code` from `vcode` where `phone` = '$VcodeExample->phone' and `type` ='$VcodeExample->type' and `ip` = '$VcodeExample->ip' and `status` = '$VcodeExample->status' order by time desc limit 1";
        $data = $conn->readConn($sql);
        return $data["code"];
    }
}